import { useModel, useLocation } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";

const useRoles = () => {
    const { remoteData } = useModel("global");
    const { state: locationState } = useLocation();

    const state = useReactive({
        roleLoading: false,
        roles: [],
        selectedRole: "",
        appLoading: false,
        applications: [],
        selectedApplication: {},
        submitLoading: false,
    });

    const loadRoles = async () => {
        state.roleLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/servicer/organization/getAuthedRoles",
            params: {
                oiUuid: window.organizationUuid,
            },
        });
        let roles = res || [];
        state.roles = roles.sort((m, u) => (m < u ? (m > u ? 1 : 0) : -1));
        state.roleLoading = false;
    };

    useEffect(() => {
        if (state.roles.length > 0) {
            if (locationState?.roleName) {
                state.selectedRole = state.roles.find((item) => item === locationState.roleName);
            } else {
                state.selectedRole = state.roles.find((item) => item === state.selectedRole);
            }
            !state.selectedRole && (state.selectedRole = state.roles[0]);
        }
    }, [state.roles]);

    const setSelectedRole = (data) => (state.selectedRole = data);

    const loadRoleApplications = async (oarName) => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/servicer/organization/getRoleApplications",
            params: {
                roleName: oarName,
            },
        });
        state.applications = res || [];
        state.appLoading = false;
    };

    useEffect(() => {
        if (state.applications.length > 0) {
            state.selectedApplication = state.applications.find((item) => item.appUuid === state.selectedApplication?.appUuid);
            !state.selectedApplication && (state.selectedApplication = state.applications[0]);
        }
    }, [state.applications]);

    const setSelectedApplication = (data) => (state.selectedApplication = data);

    const getRolesPrice = async (roles) => {
        return await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/servicer/organization/getRolesPrice",
            params: { roles },
        });
    };

    return { ...state, loadRoles, setSelectedRole, loadRoleApplications, setSelectedApplication, getRolesPrice };
};

export default useRoles;
